package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.*;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.DbUtils;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.sk.bilibili.mapper.MemberExtendMapper;

/**
* @author 邵康
* @date 2021/12/11 18:01
*/
@Service
public class MemberExtendService extends ServiceImpl<MemberExtendMapper,MemberExtend> {

    @Autowired
    private DynamicService dynamicService;

    public R<Void> add(MemberExtend memberExtend) {
        save(memberExtend);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(MemberExtend memberExtend) {
        updateById(memberExtend);
        return R.success();
    }

    public R<IPage<MemberExtend>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page,size),null));
    }

    public R<Void> topDynamic(Integer id) {
        Integer memberId= BSessionUtils.getMemberId();
        if(id!=-1){
            QueryWrapper<Dynamic> queryWrapper = QueryWrapperUtils.eq("member_id", memberId, "id", id);
            if(dynamicService.count(queryWrapper)==0)return R.error("只能置顶自己的动态");
        }
        MemberExtend memberExtend = new MemberExtend();
        memberExtend.setId(memberId);
        memberExtend.setTopDynamicId(id);
        updateById(memberExtend);
        return R.success();
    }

    public R<Dynamic> getTopDynamic(Integer memberId) {
        if(memberId==null)memberId= BSessionUtils.getMemberId();
        MemberExtend memberExtend = getById(memberId);
        Dynamic dynamic = dynamicService.getById(memberExtend.getTopDynamicId());
        if(dynamic!=null){
            dynamicService.warpDynamic(dynamic, BSessionUtils.getMemberId());
        }
        return R.success(dynamic);
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.MemberService.register'")
    public void handleMemberRegister(BiliBiliEvent<Member> event) {
        Member member = event.getData();
        MemberExtend memberExtend = new MemberExtend();
        memberExtend.setId(member.getId());
        save(memberExtend);
    }

    public R<Void> updateAnnouncement(String announcement) {
        MemberExtend memberExtend = new MemberExtend();
        memberExtend.setAnnouncement(announcement);
        memberExtend.setId(BSessionUtils.getMemberId());
        updateById(memberExtend);
        return R.success();
    }

}
